﻿using TuLing.Blazor.Dto;
using TulingMember.Core;

namespace TuLing.Blazor.Services
{
    public class FinanceService: BaseService
    {
        public FinanceService(DefaultDbContext financeRepository) : base(financeRepository) { }

        public List<Finance> SearchFinance(BaseInput input)
        {
            var search = _context.Finance.ToList();
            if (input.type > 0)
            {
                search = search.Where(m => m.FormType == input.type).ToList();
            }
            return search;
        }
        
        public Finance? GetFinance(long id)
        {
           return _context.Finance.FirstOrDefault(s => s.Id == id);
        }

        public Finance SaveFinance(Finance input)
        {
            if (input.Amount <= 0)
            {
                throw new Exception("金额必须大于0");
            }

            if (input.Id == 0)
            { 
                _context.Finance.Add(input);
                _context.SaveChanges();
                var last = _context.Finance.OrderBy(s=>s.Id).Last();
                return last;
            }
            else
            {
                _context.Update(input);
                _context.SaveChanges();
                var first = _context.Finance.First(s=>s.Id == input.Id);
                return first;
            }
        }

        public void DeleteFinance(long id)
        {
            var finance = _context.Finance.FirstOrDefault(s => s.Id == id);
            if (finance == null)
            {
                throw new Exception("账单不存在");
            }
            _context.Finance.Remove(finance);
            _context.SaveChanges();
        }
    }
}
